package com.chenhy.springbootvuesmbms.security;

import com.chenhy.springbootvuesmbms.mapper.RoleMapper;
import com.chenhy.springbootvuesmbms.mapper.UserMapper;
import com.chenhy.springbootvuesmbms.pojo.Role;
import com.chenhy.springbootvuesmbms.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LoginUser loginUser = new LoginUser();
        User user = null;


        try {
            int i = Integer.parseInt(username);
            user = userMapper.queryUserById(i);
        } catch (NumberFormatException e){
            throw new UsernameNotFoundException("应输入数字");
        }

        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        Role role = roleMapper.queryRoleById(user.getUserRole());

        loginUser.setId(user.getId());
        loginUser.setUserName(user.getUserName());
        loginUser.setUserPassword(user.getUserPassword());
        loginUser.setUserRole(user.getUserRole());
        loginUser.setRoleCode(role.getRoleCode());

        ArrayList<GrantedAuthority> authorities=new ArrayList<>();

        authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));

        loginUser.setAuthorities(authorities);

        return loginUser;

    }
}
